package com.csx.governance.traffic.mq.rocketmq;

import org.apache.rocketmq.common.message.MessageExt;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2023/4/20 17:17
 */
public class MyClassLoader extends ClassLoader{

    private final Map<String, byte[]> classes = new HashMap<>();

    public void defineClass(String name, byte[] bytes) {
        classes.put(name, bytes);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = classes.get(name);
        if (bytes == null) {
            return super.findClass(name);
        }
        return defineClass(name, bytes, 0, bytes.length);
    }

    private static byte[] loadClassData(String className) throws IOException {
        InputStream is = new FileInputStream("D:\\My Project\\demo-service-governance\\demo-traffic-governance\\demo-traffic-governance-mq\\demo-traffic-governance-mq-rocketmq\\target\\classes\\org\\apache\\rocketmq\\spring\\support\\DefaultRocketMQListenerContainer.class");
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int nextValue = is.read();
        while (nextValue != -1) {
            byteStream.write(nextValue);
            nextValue = is.read();
        }
        return byteStream.toByteArray();
    }

    public static void main(String[] args) throws Exception{
        MyClassLoader myClassLoader = new MyClassLoader();
        byte[] bytes = loadClassData("org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer");
        myClassLoader.defineClass("org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer", bytes);
        Class<?> clazz = myClassLoader.findClass("org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer");
        Object instance = clazz.newInstance();
        Method handleMessage = clazz.getMethod("handleMessage", MessageExt.class);
        Object res = handleMessage.invoke(instance, new MessageExt());
        System.out.println(res);
    }
}
